<template>
  <div>
    <page-dialog
      :title="dialogInfo.title"
      v-model:visible="shows"
      :width="dialogInfo.width"
      :bt-loading="dialogInfo.btLoading"
      :bt-list="dialogInfo.btList"
    >
      <div class="layui-row">
        <div
          v-if="isSysGroup"
          style="padding-right: 20px"
          class="layui-col-md6 select-depot-storage"
        >
          <!-- 条件栏 -->
          <NewPageFilter
            v-model:query="leftFilterInfo.query.queryMap"
            :query-more-json="true"
            :filter-list="leftFilterInfo.searchList"
            :filter-btn="leftFilterInfo.searchBtn"
          >
          </NewPageFilter>
          <dialog-table
            ref="productTable"
            v-model:data="leftTableInfo.data"
            class="productTable"
            :reserve-selection="true"
            :listen-height="false"
            :selectable="false"
            v-model:query="leftFilterInfo.query"
            :field-list="leftTableInfo.fieldList"
            :highlight-row="true"
            :check-box="false"
            :pager="false"
            :is-row-click-select="false"
            @handleEvent="leftHandleEvent"
          >
          </dialog-table>
        </div>
        <div
          class="layui-col-md6 select-depot-storage"
          :class="isSysGroup ? 'layui-col-md6' : 'layui-col-md12'"
        >
          <NewPageFilter
            v-if="isSysGroup"
            v-model:query="rightFilterInfo.query.queryMap"
            :query-more-json="true"
            :filter-list="rightFilterInfo.searchList"
            :filter-btn="rightFilterInfo.searchBtn"
          >
          </NewPageFilter>
          <el-form ref="tableForm" :model="rightTableInfo" style="width: 100%">
            <dialog-table
              ref="batchNumberTable"
              :refresh="rightTableInfo.refresh"
              :init-curpage="rightTableInfo.initCurpage"
              v-model:data="rightTableInfo.data"
              :api="rightTableInfo.api"
              :reserve-selection="true"
              :listen-height="false"
              v-model:query="rightFilterInfo.query"
              :field-list="rightTableInfo.fieldList"
              :check-box="false"
              :pager="!sacnData.length"
              :highlight-row="true"
              @handleEvent="rightHandleEvent"
            >
              <template v-slot:col-editQty="scope">
                <el-form-item
                  v-if="
                    canEdit
                      ? true
                      : scope.row.codeType === 1 || scope.row.codeType === 4
                  "
                  class="margin-bottom"
                  @click.stop=""
                >
                  <div class="page-table-input-number-wrapper">
                    <div class="page-table-input-number-left">
                      <div class="page-table-input-number-item">
                        <el-form-item>
                          <el-input-number
                            v-model.lazy="scope.row.largeUnitQty"
                            style="width: 100%"
                            clearable
                            controls-position="right"
                            :precision="
                              scope.row.qtyOperateMode === 0 ||
                              scope.row.qtyOperateMode === 2
                                ? 0
                                : systemConfig.qty_show_precision
                            "
                            :min="0"
                            :max="largeMax(scope.row)"
                            @change="changeLarge($event, scope.row)"
                          />
                        </el-form-item>
                        <div class="page-table-input-number-item-unite">
                          {{ scope.row.unitName }}
                        </div>
                      </div>
                      <div
                        v-if="
                          scope.row.unitConvertCoefficient > 1 &&
                          scope.row.qtyOperateMode === 2
                        "
                        class="page-table-input-number-item"
                      >
                        <el-form-item>
                          <el-input-number
                            v-model.lazy="scope.row.smallUnitQty"
                            style="width: 100%"
                            clearable
                            controls-position="right"
                            :precision="0"
                            :min="0"
                            :max="smallMax(scope.row)"
                          />
                        </el-form-item>
                        <div class="page-table-input-number-item-unite">
                          {{ scope.row.calcUnitName }}
                        </div>
                      </div>
                    </div>
                    <div
                      v-if="scope.row.qtyOperateMode === 2"
                      class="page-table-input-number-right"
                    >
                      {{ $fn.qtyFormatter(scope.row.editQty) }}
                    </div>
                  </div>
                </el-form-item>
                <span
                  v-else-if="
                    canEd
                      ? false
                      : scope.row.codeType === 2 || scope.row.codeType === 3
                  "
                  >{{ $fn.qtyFormatter(scope.row.editQty) }}</span
                >
              </template>
            </dialog-table>
          </el-form>
        </div>
      </div>
    </page-dialog>
  </div>
</template>

<script setup name="selectScanDepotStorage">
import PageDialog from '../PageDialog/index'
import DialogTable from '../DialogTable/index'
import NewPageFilter from '../NewPageFilter/index'
import { getDepotStockCustomizeListPage } from '@/api/stock.js'
import { getCustomizeSetting } from '@/api/customize'
import _ from 'lodash'
const emits = defineEmits()
const { proxy } = getCurrentInstance()
const props = defineProps({
  highlightRow: {
    type: Boolean,
    default: true,
  },
  canEdit: {
    type: Boolean,
    default: false,
  },
  checkBox: {
    type: Boolean,
    default: true,
  },
  isFill: {
    type: Boolean,
    default: true,
  },
  api: {
    type: Function,
    default: getDepotStockCustomizeListPage,
  },
  excludeQueryList: {
    type: Array,
    default: function () {
      return []
    },
  },
  showPrice: {
    type: Boolean,
  },
  showDialog: {
    type: Boolean,
  },
  leftTableKey: {
    type: String,
    default:
      'productPageWithDepotStockLeft-com.slip.spd.entity.vo.stock.DepotStockVO',
  },
  rightTableKey: {
    type: String,
    default:
      'productPageWithDepotStockRight-com.slip.spd.entity.vo.stock.DepotStockVO',
  },
  query: {
    type: Object,
    default: function () {
      return {}
    },
  },
  rightQueryParams: {
    type: Object,
    default: function () {
      return {}
    },
  },
  leftQueryParams: {
    type: Object,
    default: function () {
      return {}
    },
  },
  stockIdStr: {
    type: String,
    default: 'depotStockId',
  },
  sacnData: {
    type: Array,
    default: () => {
      return []
    },
  },
})

// 过滤相关配置
const systemConfig = ref(proxy.$store.state.permission.systemConfig)
const leftFilterInfo = ref({
  query: {
    queryParams: {
      //stockAvailableCalcQtyGt: 0
      ...props.query.queryParams,
    },
    queryMap: {
      ...props.query,
    },
    customizeUserVO: {},
  },
  searchList: [],
  searchBtn: [{ type: 'button', label: '搜索', event: leftSearch }],
})
const isSysGroup = ref(false)
// 表格相关
const leftTableInfo = ref({
  refresh: 1,
  initCurpage: 1,
  api: undefined,
  height: '70%',
  data: [],
  fieldList: [],
})
const rightFilterInfo = ref({
  query: {
    queryParams: {
      stockAvailableCalcQtyGt: 0,
      ...props.query.queryParams,
    },
    queryMap: {
      id: {
        queryType: 'IN',
        value: '',
      },
    },
    customizeUserVO: {},
  },
  data: {
    fill: false,
  },

  searchList: [],
  searchBtn: [
    { type: 'button', label: '搜索', event: rightSearch },
    { type: 'slot', value: 'fill' },
  ],
})
// 表格相关
const rightTableInfo = ref({
  refresh: 1,
  initCurpage: 1,
  api: undefined,
  height: '70%',
  data: [],
  fieldList: [],
})
// 弹窗相关
const dialogInfo = ref({
  title: '选择库存产品',
  btLoading: false,
  width: '90%',
  btList: [
    { label: '关闭', event: handleClose, show: true },
    {
      label: '保存',
      type: 'primary',
      disabled: true,
      event: save,
      show: true,
    },
  ],
})
const selectRow = ref({})
const clickRow = ref({})
const searchObj = ref(undefined)
const groupArr = ref(undefined)

const shows = computed({
  get() {
    return props.showDialog
  },
  set(newValue) {
    emits('update:showDialog', newValue) // 更新父组件shows
  },
})

watch(
  () => rightTableInfo.value.data,
  (val) => {
    if (val.length) {
      val.forEach((row) => {
        if (row.codeType === 1 || row.codeType === 4 || props.canEdit) {
          let smallUnitQty = parseFloat(row.smallUnitQty || 0)
          let unitConvertCoefficient = row.unitConvertCoefficient || 1
          let largeUnitQty = parseFloat(row.largeUnitQty || 0)
          let editCalcQty = proxy.$fn.accAdd(
            proxy.$fn.accMul(largeUnitQty, unitConvertCoefficient),
            smallUnitQty
          )
          let editQty = proxy.$fn.accDiv(editCalcQty, unitConvertCoefficient)
          row.editCalcQty = editCalcQty
          row.editQty = editQty
          row.sumAmount = proxy.$fn.accDiv(
            proxy.$fn.accMul(editCalcQty, row.price),
            unitConvertCoefficient
          )
        }
      })
    }
  },
  {
    deep: true,
  }
)

setData()
function setData() {
  let obj = {
    price: {
      label: '单价',
      value: 'price',
      type: 'column',
      componentType: 'price',
      permission: !props.showPrice,
      formatter: proxy.$fn.TripartiteMethod,
      hidden: true,
      show: false,
    },
    sumAmount: {
      label: '总金额',
      value: 'sumAmount',
      formatter: proxy.$fn.TripartiteMethod,
      type: 'column',
      componentType: 'price',
      permission: !props.showPrice,
      hidden: true,
      show: false,
    },
    defaultSupplierPrice: {
      label: '默认供应商价格',
      value: 'defaultSupplierPrice',
      type: 'column',
      componentType: 'price',
      permission: !props.showPrice,
      formatter: proxy.$fn.TripartiteMethod,
      hidden: true,
      show: false,
    },
  }
  leftTableInfo.value.fieldList = Object.values({
    ...proxy.$fn.deepClone(proxy.$fieldfList.FieldList),
    ...proxy.$fn.deepClone(obj),
  })
  rightTableInfo.value.fieldList = Object.values({
    ...proxy.$fn.deepClone(proxy.$fieldfList.FieldList),
    ...proxy.$fn.deepClone(obj),
    editQty: {
      label: '数量',
      value: 'editQty',
      type: 'slot',
      componentType: 'number',
      show: false,
      hidden: true,
      minWidth: '250px',
    },
  })
  rightFilterInfo.value.searchList = Object.values({
    ...proxy.$fn.deepClone(proxy.$fieldfList.FieldList),
    ...proxy.$fn.deepClone(obj),
    commonName: {
      label: '通用名称',
      value: 'commonName',
      componentType: 'input',
      show: false,
      hidden: true,
    },
  })
  leftFilterInfo.value.searchList = Object.values({
    ...proxy.$fn.deepClone(proxy.$fieldfList.FieldList),
    ...proxy.$fn.deepClone(obj),
    commonName: {
      label: '通用名称',
      value: 'commonName',
      componentType: 'input',
      show: false,
      hidden: true,
    },
  })
  proxy.$nextTick(() => {
    getLeftCustomize()
  })
}

function largeMax(row) {
  if (row.qtyOperateMode === 2) {
    return parseInt(row.availableCalcQty / row.unitConvertCoefficient)
  } else {
    return row.availableQty
  }
}
function smallMax(row) {
  let largeUnitQty = parseInt(row.availableCalcQty / row.unitConvertCoefficient)
  if (largeUnitQty === 0 || row.largeUnitQty === largeUnitQty) {
    return parseInt(row.availableCalcQty % row.unitConvertCoefficient)
  } else {
    return row.unitConvertCoefficient - 1
  }
}
function changeLarge(e, row) {
  let largeUnitQty = parseInt(row.availableCalcQty / row.unitConvertCoefficient)
  if (row.qtyOperateMode === 2 && row.unitConvertCoefficient > 1) {
    if (largeUnitQty > 0 && e === largeUnitQty) {
      let smallUnitQty = parseInt(
        row.availableCalcQty % row.unitConvertCoefficient
      )
      if (row.smallUnitQty > smallUnitQty) {
        row.smallUnitQty = smallUnitQty
      }
    }
  }
}
// 获取左侧产品列表
function getLeftList() {
  leftTableInfo.value.data = props.sacnData
}
function leftSearch() {}
function getRightList() {
  rightTableInfo.value.refresh = Math.random()
}
function rightSearch() {
  rightTableInfo.value.initCurpage = Math.random()
  rightTableInfo.value.refresh = Math.random()
}

function save() {
  //条码类型 code_type：1无码，2系统唯一码，3原厂码，4批次码
  let selectRowItem = proxy.$fn.deepClone(selectRow.value)
  let clickRowItem = proxy.$fn.deepClone(clickRow.value)
  if (isSysGroup.vlaue) {
    if (props.canEdit) {
      selectRowItem.calcQty = selectRowItem.editCalcQty
      selectRowItem.qty = selectRowItem.editQty
    }
    clickRowItem.largeUnitQty = selectRowItem.largeUnitQty
    clickRowItem.smallMax = selectRowItem.smallMax
    clickRowItem.calcQty = selectRowItem.calcQty
    clickRowItem.qty = selectRowItem.qty
    clickRowItem.sumAmount = selectRowItem.sumAmount
    emits('callback', [clickRowItem], selectRowItem)
  } else {
    if (props.canEdit) {
      selectRowItem.calcQty = selectRowItem.editCalcQty
      selectRowItem.qty = selectRowItem.editQty
    }
    emits('callback', [proxy.$fn.deepClone(selectRowItem)], selectRowItem)
  }

  handleClose()
}
function leftHandleEvent(event, data) {
  switch (event) {
    case 'tableClickRow':
      if (data && data.id) {
        console.log(data)
        data[props.stockIdStr] = data.id
        rightFilterInfo.value.query.queryMap.id.value = data.groupConcatIds
        rightTableInfo.value.api = props.api
        clickRow.value = data
        rightSearch()
      }
      break
  }
}
function rightHandleEvent(event, data) {
  switch (event) {
    case 'list':
      if (data.length) {
        data.forEach((row) => {
          if (row.codeType === 1 || row.codeType === 4) {
            if (row.availableQty >= 0) {
              row.largeUnitQty = 1
              row.smallUnitQty = 0
            } else {
              row.largeUnitQty = 0
              row.smallUnitQty = row.availableCalcQty
            }
          } else if (row.codeType === 2 || row.codeType === 3) {
            if (props.canEdit) {
              if (row.availableQty >= 0) {
                row.largeUnitQty = 1
                row.smallUnitQty = 0
              } else {
                row.largeUnitQty = 0
                row.smallUnitQty = row.availableCalcQty
              }
            } else {
              row.editCalcQty = row.calcQty
              row.editQty = row.qty
            }
          }
          row[props.stockIdStr] = row.id
        })
        rightTableInfo.value.data = data
      }
      break
    case 'tableClickRow':
      selectRow.value = data
      break
  }
  if (selectRow.value && selectRow.value.id) {
    dialogInfo.value.btList[1].disabled = false
  } else {
    dialogInfo.value.btList[1].disabled = true
  }
}
// 关闭弹窗前的回调
function handleClose() {
  shows.value = false
  emits('reset')
}
function getLeftCustomize() {
  let param = { tableKey: props.leftTableKey }
  let obj = {}
  let _groupArr = []
  getCustomizeSetting(param).then((res) => {
    if (res && res.success) {
      let data = res.data
      leftTableInfo.value.fieldList = proxy.$fn.setFieldList(
        leftTableInfo.value.fieldList,
        data.detail
      )
      isSysGroup.value = false
      for (let key in data.detail) {
        if (data.detail[key].sysGroupLevel > 0) {
          obj[key] = {
            queryType: 'EQUALS',
            queryCategory: 'AND',
            ignoreEmptyValue: false,
            value: null,
          }
          _groupArr.push({ value: key })
          isSysGroup.value = true
        }
      }
      proxy.$nextTick(() => {
        searchObj.value = obj
        groupArr.value = _groupArr

        rightFilterInfo.value.query.excludeQueryList = props.excludeQueryList
      })
      getRightCustomize()
      if (isSysGroup.value) {
      }
      getLeftList()
    }
  })
}
function getRightCustomize() {
  let param = { tableKey: props.rightTableKey }
  getCustomizeSetting(param).then((res) => {
    if (res && res.success) {
      let data = res.data
      rightFilterInfo.value.query.customizeUserVO = data
      rightTableInfo.value.fieldList = proxy.$fn.setFieldList(
        rightTableInfo.value.fieldList,
        data.detail
      )
      let searchInfo = proxy.$fn.setSearchList(
        rightFilterInfo.value.searchList,
        data.detail
      )
      rightFilterInfo.value.searchList = searchInfo.searchList
      rightFilterInfo.value.searchList.forEach((item) => {
        item.event = leftSearch
      })
      rightFilterInfo.value.query.queryMap = {
        ...searchInfo.queryMap,
        ...rightFilterInfo.value.query.queryMap,
      }
      rightFilterInfo.value.query.queryParams = {
        ...rightFilterInfo.value.query.queryParams,
        ...props.query.queryParams,
        ...props.rightQueryParams,
      }
      rightTableInfo.value.api = props.api
      if (!isSysGroup.value) {
        rightTableInfo.value.data = props.sacnData
        rightTableInfo.value.data.forEach((row) => {
          if (row.availableQty >= 0) {
            row.largeUnitQty = 1
            row.smallUnitQty = 0
          } else {
            row.largeUnitQty = 0
            row.smallUnitQty = row.availableCalcQty
          }
        })
      }
      //   getRightList()
    }
  })
}
</script>

<style scoped lang="scss">
.productTable :deep(.el-table__header-wrapper) .el-checkbox {
  display: none;
}
.productTable
  :deep(.el-checkbox__input.is-disabled.is-checked)
  .el-checkbox__inner {
  background-color: #6dc1a9;
  border-color: #6dc1a9;
}
.productTable
  :deep(.el-checkbox__input.is-disabled.is-checked)
  .el-checkbox__inner::after {
  border-color: #ffffff;
}
</style>
